package com.sword.www.designPattern.singleton;

import java.io.*;
import java.lang.reflect.Constructor;

/**
 * 静态内部类单例模式
 * @author linmeng
 * @version 1.0
 * @date 2021年11月9日 21:25
 */
public class StaticNestSingleton implements Serializable{

    private StaticNestSingleton(){}

    private static class SingletonHolder{
        private static final StaticNestSingleton SINGLETON = new StaticNestSingleton();
    }
    /**
     *
     * 直接返回
     * @author linmeng
     * @date 2021年11月9日 21:44
     * @return com.sword.www.designPattern.singleton.EagerSingleton
     */
    public static StaticNestSingleton getStaticNestInstance(){

        return SingletonHolder.SINGLETON;
    }

    public static void main(String[] args) throws Exception{
        Constructor<StaticNestSingleton> constructor = StaticNestSingleton.class.getDeclaredConstructor();
        constructor.setAccessible(true);
        StaticNestSingleton staticNestSingleton = constructor.newInstance();
        System.out.println(staticNestSingleton==StaticNestSingleton.getStaticNestInstance());

        // 创建文件输出流
        ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("StaticNestSingleton.file"));
        // 写入文件
        outputStream.writeObject(StaticNestSingleton.getStaticNestInstance());
        // 文件中读取单例对象
        File file = new File("StaticNestSingleton.file");
        ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(file));
        StaticNestSingleton staticNestSingleton2 = (StaticNestSingleton) inputStream.readObject();
        System.out.println(staticNestSingleton2==StaticNestSingleton.getStaticNestInstance());
    }
}
